package com.winit.openapi.interceptor.validator.impl;

import java.util.TimeZone;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.BpartnerService;
import com.winit.erp.spi.bpartner.command.BpartnerCommand;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.erp.spi.user.UserService;
import com.winit.erp.spi.user.command.UserCommand;
import com.winit.erp.spi.user.vo.User;
import com.winit.openapi.apiadapter.adapter.UmsUserServiceAdapter;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.interceptor.validator.BasicAPIRequestValidator;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.util.RequestUtil;
import com.winit.openapi.util.ValidateUtil;
@Service("basicRequestHandler")
public class BasicRequestHandler extends BasicAPIRequestValidator<HttpServletRequest> {

    private static final Logger   logger = LoggerFactory.getLogger(BasicRequestHandler.class);

    @Resource
    private UserService           userService;
    @Resource
    private BpartnerService       bpartnerService;
    @Resource
    private UmsUserServiceAdapter umsUserServiceAdapter;

    @Override
    public void checkUser(HttpServletRequest request) throws ApiException {
        RequestMsg requestMsg = RequestUtil.getRequestMsg(request);
        if (StringUtils.isBlank(requestMsg.getApp_key())) {
            return;
        }
        User user = umsUserServiceAdapter.queryUserByNameAndPlatform(requestMsg.getApp_key(), requestMsg.getPlatform());
        if (user == null || user.getBpartnerId() == null || user.getBpartnerId().longValue() == 0) {
            logger.warn("UMS查询用户信息失败，查询ERP系统，User:" + requestMsg.getApp_key());
            // 兼容处理，UMS查询用户失败，则去ERP查询
            UserCommand userCommand = new UserCommand();
            userCommand.setLoginName(requestMsg.getApp_key());
            user = userService.getUser(userCommand);
            if (user == null) {
                throw new ApiException(ErrorCode.USER_NOT_FOUND);
            }
        }
        Bpartner bpartner = umsUserServiceAdapter.queryBpartnerByUser(user, requestMsg.getPlatform());
        if (bpartner == null || bpartner.getcBpartnerId() == null || bpartner.getcBpartnerId().longValue() == 0) {
            logger.warn("UMS查询用户公司信息失败，查询ERP系统，User:" + requestMsg.getApp_key() + " BpartnerId:" + user.getBpartnerId());
            BpartnerCommand command = new BpartnerCommand();
            command.setcBpartnerId(user.getBpartnerId());
            bpartner = bpartnerService.queryBpartnerById(command);
            if (bpartner == null) {
                throw new ApiException(ErrorCode.BPARTNER_NOT_FOUND_ERROR);
            }
        }
        // 设置用户上下文信息
        CommandContext ctx = CommandContext.getContext();
        ctx.set(ApiConstant.API_USER, user);
        ctx.set(ApiConstant.API_BPARTNER, bpartner);
        ctx.setUsername(user.getLoginName());
        ctx.setUserId(bpartner.getcBpartnerId().toString());
        ctx.setOrgId(bpartner.getAdOrgId());
        ctx.setTimeZone(TimeZone.getDefault());
    }

    @Override
    public void checkUserSign(HttpServletRequest request) throws ApiException {
        RequestMsg requestMsg = RequestUtil.getRequestMsg(request);
        if (requestMsg == null) {
            return;
        }

        String sign = requestMsg.getSign();
        CommandContext ctx = CommandContext.getContext();
        User user = ctx.get(ApiConstant.API_USER);
        checkSign(request, user.getToken(), sign);
    }

    @Override
    public void doAuth(HttpServletRequest request) {
        checkUser(request);
        checkUserSign(request);

    }

    @Override
    public void doCheckData(HttpServletRequest request) throws ApiException {
        JSONObject json = super.checkBaseData(request);
        ValidateUtil.validNotNull(json, "app_key");
        ValidateUtil.validMaxLength(json, "app_key", 50);
        // sign
        ValidateUtil.validNotNull(json, "sign");
        ValidateUtil.validMaxLength(json, "sign", 32);

    }

}
